import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getUserInfoService,
  updateBalanceService,
  addUserService,
  updateUserInfoService,
  updatePasswordService
} from '@/api/user'

export const useUserStore = defineStore(
  'user-1',
  () => {
    const token = ref('')
    const setToken = (newToken) => {
      token.value = newToken
      /* getUser(newToken) */
    }
    const removeToken = () => {
      if (user.value.jzmm === '0') {
        token.value = ''
        user.value = {}
      }
    }

    const user = ref({})
    const updateUseInfo = async (obj) => {
      await updateUserInfoService(obj)
      console.log(obj)

      await getUser(obj.id)
    }
    const getUser = async (id) => {
      const res = await getUserInfoService(id)
      user.value = res.data
      console.log(res.data)
      console.log(user.value)
    }
    const updateMoney = async (id, money) => {
      await updateBalanceService(id, money)
    }
    const setUser = (obj) => {
      user.value = obj
    }

    const addUser = async (obj) => {
      await addUserService(obj)
    }

    const updatePassword = async (obj) => {
      console.log(obj)
      await updatePasswordService(obj)
    }
    return {
      token,
      setToken,
      removeToken,
      user,
      getUser,
      setUser,
      updateMoney,
      addUser,
      updateUseInfo,
      updatePassword
    }
  },
  {
    persist: true
  }
)
